package ctrl.action.impl;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Model;
import model.beans.ItemBean;

import util.ProjectConstants;

import ctrl.action.ServletAction;

public class CategoryServletAction implements ServletAction{
	
	private ServletContext context;	
	public CategoryServletAction(ServletContext context) {
		this.context = context;
	}
	
	@Override
	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		
		String jsp;
		HttpSession session = request.getSession();	
		String selectedCategory = request.getParameter(ProjectConstants.PARAMCATEGORYID);
		Model model = (Model)context.getAttribute(ProjectConstants.PARAMMODEL);
		List<ItemBean> itemList = (List<ItemBean>)model.getItemListByCatalogID(selectedCategory);				
		
		//For returning page after login
		String previousPage = ProjectConstants.PARAMCATEGORY + "?" + ProjectConstants.PARAMCATEGORYID + "=" + selectedCategory;
		session.setAttribute(ProjectConstants.PARAMPREVIOUSPAGE, previousPage);
		
		if(itemList != null && itemList.size() > 0){
			request.setAttribute(ProjectConstants.PARAMITEMLIST, itemList);			
			jsp = ProjectConstants.PAGECATEGORY;
		}
		else{
			jsp = ProjectConstants.PAGEERROR;
		}
		
		context.getRequestDispatcher("/" + jsp + ".jspx").forward(request, response);		
	}
}
